package com.weixing.mall.provider.config;

import com.weixing.mall.provider.support.mq.DivideStockRedisMessage;
import com.weixing.mall.redis.RedisKeyConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class CmsRedisConfig {

    private static final Logger log = LoggerFactory.getLogger(CmsRedisConfig.class);

    @Autowired
    private DivideStockRedisMessage divideStockRedisMessage;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 方法描述: 数据库减库存监听器
     * @Author Small
     * @Date 2020/4/11 15:29
     * @return
     */
    @Bean
    public MessageListenerAdapter stockDivideAdapter() {
        // onMessage 如果RedisMessage 中 没有实现接口，这个参数必须跟RedisMessage中的读取信息的方法名称一样
        return new MessageListenerAdapter(divideStockRedisMessage, "onMessage");
    }





    /**
     * redis消息监听器容器
     * 可以添加多个监听不同话题的redis监听器，只需要把消息监听器和相应的消息订阅处理器绑定，该消息监听器
     * 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
     * @param redisConnectionFactory
     * @param stockDivideAdapter
     * @return
     */
    @Bean
    public RedisMessageListenerContainer stockDivideContainer(RedisConnectionFactory redisConnectionFactory,
                                                              MessageListenerAdapter stockDivideAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        //订阅频道
        container.addMessageListener(stockDivideAdapter, new PatternTopic(RedisKeyConst.TOPIC_ACT_ITEM_DIVIDE_STOCK));
        return container;
    }

}
